package org.codehaus.activemq.store.jdbc;

import java.sql.Connection;
import java.util.LinkedList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class TransactionContext
{
  private static final Log log = LogFactory.getLog(TransactionContext.class);
  private static ThreadLocal threadLocalTxn = new ThreadLocal();

  public static Connection getConnection()
  {
    LinkedList list = (LinkedList)threadLocalTxn.get();
    if ((list != null) && (!list.isEmpty())) {
      return (Connection)list.getFirst();
    }
    throw new IllegalStateException("Attempt to get a connection when no transaction in progress");
  }

  public static Connection popConnection()
  {
    LinkedList list = (LinkedList)threadLocalTxn.get();
    if ((list == null) || (list.isEmpty())) {
      log.warn("Attempt to pop connection when no transaction in progress");
      return null;
    }

    return (Connection)list.removeFirst();
  }

  public static void pushConnection(Connection connection)
  {
    LinkedList list = (LinkedList)threadLocalTxn.get();
    if (list == null) {
      list = new LinkedList();
      threadLocalTxn.set(list);
    }
    list.addLast(connection);
  }

  public static int getTransactionCount() {
    LinkedList list = (LinkedList)threadLocalTxn.get();
    if (list != null) {
      return list.size();
    }
    return 0;
  }
}